<?php

namespace App\Http\Controllers\Admin\Framework\Common;

use App\Http\Controllers\Admin\ParentController;
use App\Http\FormValidator\Admin\Framework\PassportSubmit;
use App\Http\Request\Admin\Framework\Common\PassportSubmitRequest;
use App\Master\Framework\Extend\Core;
use App\Master\Framework\Extend\Module;
use App\Master\Framework\Extend\Verify;
use App\Models\Admin\Framework\AdminLoginLogModel;
use App\Models\Admin\Framework\AdminUsersModel;
use App\Utils\AppResult;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;
use Jenssegers\Agent\Agent;

class PassportController extends ParentController
{

    public function __construct(array $attributes = [])
    {
        parent::__construct();
    }

    public function login(Request $request)
    {
        if (!$settings = Module::_SetupModule('SiteSettings')) {
            $settings = [
                'login_bg'    => '',
                'login_logo'  => '',
                'login_title' => '鲸蓝管理系统',
                'left_logo'   => '',
                'left_title'  => '鲸蓝管理系统',
            ];
        }
        $settings['favicon'] = isset($settings['favicon']) ? $settings['favicon'] : '/favicon.ico';
        return view('admin.framework.common.login', ['settings' => $settings]);
    }

    public function submit(PassportSubmitRequest $request)
    {
        // 参数接管
        $params = $request->all();
        $settings = Module::_SetupModule('SiteSettings');
        $settings['admin_log'] = $settings['admin_log'] ?? 'true';

        // IP 校验
        if(isset($settings['admin_ips']) && $settings['admin_ips']) {
            if(!$this->ipInNetwork($settings['admin_ips'])) {
                $this->adminLoginEvent($request->account,1,$settings['admin_log'],0,'访问IP受限',1011);
                return AppResult::response201('访问IP受限！');
            }
        }

        // 校验滑动验证
        if (!$params['captcha']) {
            $this->adminLoginEvent($request->account,1,$settings['admin_log'],0,'请拖动滑块进行验证',1001);
            return AppResult::response201('请先进行验证！');
        }

        // 校验账号格式
        if (!Verify::account($params['account'], 5)) {
            $this->adminLoginEvent($request->account,1,$settings['admin_log'],0,'登录账号或密码错误',1002);
            return AppResult::response201('登录账号或密码错误！');
        }

        // 校验密码格式
        if (!Verify::password($params['password'], 5)) {
            $this->adminLoginEvent($request->account,1,$settings['admin_log'],0,'登录账号或密码错误',1003);
            return AppResult::response201('登录账号或密码错误！');
        }

        if (!$users = AdminUsersModel::where(['account' => $params['account'], 'status' => 1, 'is_delete' => 0])->first()) {
            $this->adminLoginEvent($request->account,1,$settings['admin_log'],0,'登录账号或密码错误',1004);
            return AppResult::response201('登录账号或密码错误！');
        }

        if (!Hash::check(md5($params['password']), $users->password)) {
            $this->adminLoginEvent($request->account,$users->is_show,$settings['admin_log'],$users->id,'登录账号或密码错误',1005);
            return AppResult::response201('登录账号或密码错误！');
        }

        $uuid = Str::uuid();

        AdminUsersModel::query()->where('id', $users->id)->update([
            'uuid'      => $uuid,
            'login_num' => $users->login_num + 1,
            'login_at'  => time()
        ]);

        session()->put('adminUsersUUID', $uuid);
        Auth::guard('admin')->login($users);

        $this->adminLoginEvent($request->account,$users->is_show,$settings['admin_log'],$users->id,'登录成功',200);
        return AppResult::response200('登录成功');
    }

    public function logout()
    {
        Auth::guard('admin')->logout();

        Core::setCookie('9ca8e8d13b4369cddfdab26c63d69ce2', null, -1);

        Core::setCookie('f63dcfe3c89a14e80c9cdf60b4b94f4b', null, -1);
        $prefix = config('admin.prefix');
        return redirect("/{$prefix}/passport/login");
    }

    public function adminLoginEvent($account, $is_show, $is_login, $user_id, $msg, $code)
    {
        if ($is_login == 'false' || !$is_show) {
            return false;
        }

        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } else {
            $ip = request()->getClientIp();
        }

        $insert = [
            'account'    => $account,
            'user_id'    => $user_id,
            'code'       => $code,
            'msg'        => $msg,
            'ip'         => $ip,
            'browser'    => (new Agent())->browser(),
            'region'     => Core::getIpRegion($ip),
            'created_at' => time()
        ];
        return AdminLoginLogModel::query()->insert($insert);
    }

    public function ipInNetwork($network)
    {
        if (empty($network) || $network == '*') {
            return true;
        }

        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } else {
            $ip = Request::capture()->getClientIp();
        }

        if ($ip == '127.0.0.1'){
            return true;
        }

        if ($network_maps = explode(',', $network)) {
            if (!in_array($ip,$network_maps)){
                return false;
            }
        }

        return true;
    }
}